package com.sansecy.monitor.see;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.util.Pair;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.sansecy.monitor.DrawableUtils;
import com.sansecy.monitor.dialog.ErrorDialog;
import com.sansecy.monitor.dialog.LogDetailDialog;
import com.sansecy.monitor.dialog.SettingDialog;
import com.sansecy.monitor.utils.Utils;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description 日志视图，包含一个recyclerView和一个LinearLayout
 * @Date 2019-08-03 20:03
 * @Created by caoyu
 */
public class LogView extends LinearLayout {

    public static final int TEXT_SIZE = 18;
    public static LogAdapter mLogAdapter = new LogAdapter();
    private static int mDp12;
    private static int mDp5;
    private static int mDp2;
    private static int dp45;
    private static int dp75;
    private static int dp50;
    //使用applicationContext创建的RecyclerView
    @SuppressLint("StaticFieldLeak")
    private static RecyclerView mRecyclerView;
    private final LinearLayoutManager mLayoutManager;
    //    private final int mTouchSlop;

    public LogView(Context context) {
        super(context);
        setOrientation(HORIZONTAL);
        mRecyclerView = new RecyclerView(context);
        mRecyclerView.setAdapter(mLogAdapter);
        mLayoutManager = new LinearLayoutManager(context, RecyclerView.VERTICAL, true);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setLayoutParams(new MarginLayoutParams(Utils.dpToPx(context, 200), ViewGroup.LayoutParams.WRAP_CONTENT));
        this.addView(mRecyclerView);

        LinearLayout optionMenuContainer = new LinearLayout(context);
        optionMenuContainer.setOrientation(VERTICAL);
        GradientDrawable drawable = DrawableUtils.createDrawable(DrawableUtils.RECTANGLE, Color.RED, 0, 0, Utils.dpToPx(context, 6));
        mDp12 = Utils.dpToPx(context, 12);
        mDp5 = Utils.dpToPx(context, 5);
        mDp2 = Utils.dpToPx(context, 2);
        dp45 = Utils.dpToPx(context, 45);
        dp50 = Utils.dpToPx(context, 50);
        dp75 = Utils.dpToPx(context, 75);

        TextView tvSetting = createTextView(context, "设置");
        tvSetting.setBackground(drawable);
        tvSetting.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                SettingDialog dialog = new SettingDialog(ActivityManger.getTopActivity());
                dialog.show();
            }
        });
        optionMenuContainer.addView(tvSetting);

        TextView tvClear = createTextView(context, "清空");
        ((MarginLayoutParams) tvClear.getLayoutParams()).topMargin = mDp5;
        tvClear.setBackground(drawable);
        tvClear.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                sLogBeans.clear();
                mLogAdapter.notifyDataSetChanged();
            }
        });
        optionMenuContainer.addView(tvClear);

//        TextView tvFilter = createTextView(context, "过滤");
//        ((MarginLayoutParams) tvFilter.getLayoutParams()).topMargin = mDp5;
//        tvFilter.setBackground(drawable);
//        optionMenuContainer.addView(tvFilter);

        this.addView(optionMenuContainer);
        for (final Pair pair : SeePluginLoader.getAppPlugins()) {
            TextView textView = createTextView(context, String.valueOf(pair.first));
            ((MarginLayoutParams) textView.getLayoutParams()).topMargin = mDp5;
            textView.setBackground(DrawableUtils.getShape(-16776961, 6));
            textView.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (pair.second != null) {
                        ((Runnable) pair.second).run();
                    }
                }
            });
            optionMenuContainer.addView(textView);
        }
//        ViewConfiguration configuration = ViewConfiguration.get(context);
//        mTouchSlop = configuration.getScaledTouchSlop();

    }

    private TextView createTextView(Context context, String text) {
        TextView textView = new TextView(context);
        textView.setLayoutParams(new MarginLayoutParams(dp75, dp50));
        textView.setText(text);
        textView.setGravity(Gravity.CENTER);
        textView.setBackgroundColor(Color.RED);
        if (text.length() <= 2) {
            textView.setTextSize(TEXT_SIZE);
        } else if (text.length() == 3) {
            textView.setTextSize(16);
        } else if (text.length() == 4) {
            textView.setTextSize(15);
        }else if (text.length() == 5) {
            textView.setTextSize(14);
        }
        textView.setTextColor(Color.WHITE);
        MarginLayoutParams params = new LinearLayout.MarginLayoutParams(dp75, dp50);
        textView.setLayoutParams(params);
        return textView;
    }

    private float moveX;
    private float moveY;
    private int downX;
    private int downY;

    @Override
    public boolean onInterceptTouchEvent(MotionEvent event) {
        boolean intercepted = false;
        float x = event.getX();
        float y = event.getY();
        int action = event.getAction();
        switch (action) {
            case MotionEvent.ACTION_DOWN:
                downX = (int) x;
                downY = (int) y;
                intercepted = false;
                break;
            case MotionEvent.ACTION_MOVE:
                moveX = event.getX();
                moveY = event.getY();
                float deltaX = Math.abs(moveX - downX);
                float deltaY = Math.abs(moveY - downY);
                double sqrt = Math.sqrt(deltaX * deltaX + deltaY * deltaY);
                int deg = Math.round((float) (Math.asin(deltaY / sqrt) / Math.PI * 180));// 角度
                if (moveY < downY && deg > 45) {// 上
                    Log.d("onTouch-ACTION_MOVE", "角度:" + deg + ", 动作:上");
//                    intercepted = !(moveY > 0) || !(moveY < mRecyclerView.getHeight());
//                    if (mLayoutManager.findLastCompletelyVisibleItemPosition() == mLayoutManager.getChildCount() - 1) {
//                        intercepted = true;
//                    }
                } else if (moveY > downY && deg > 45) {// 下
                    Log.d("onTouch-ACTION_MOVE", "角度:" + deg + ", 动作:下");
//                    intercepted = !(moveY > 0) || !(moveY < mRecyclerView.getHeight());
//                    if (mLayoutManager.findLastCompletelyVisibleItemPosition() == 0) {
//                        intercepted = true;
//                    }
                } else if (moveX < downX && deg <= 45) {// 左
                    Log.d("onTouch-ACTION_MOVE", "角度:" + deg + ", 动作:左");
                    intercepted = true;
                    // 原方向不是向右時，方向轉右
                } else if (moveX > downX && deg <= 45) {// 右
                    Log.d("onTouch-ACTION_MOVE", "角度:" + deg + ", 动作:右");
                    intercepted = true;
                    // 原方向不是向左時，方向轉右
                }
                break;
        }
        return intercepted;
    }

//        float x = event.getX();
//        float y = event.getY();
//        switch (event.getAction()) {
//
//            case MotionEvent.ACTION_DOWN://按下时
//
//                startX = x;//获得按下时的X坐标
//
//                startY = y;//获得按下时的Y坐标
//
//                offsetsByX = 0;//设置X轴方向总偏移量
//
//                offsetsByY = 0;//设置Y轴方向总偏移量
//
//                break;
//
//            case MotionEvent.ACTION_MOVE:
//
//                movedX = x;//获得移动时候的X坐标
//
//                movedY = y;//获得移动时候的Y坐标
//
//                offsetX = startX - movedX;//获得X轴的偏移量
//
//                offsetY = startX - movedY;//获得Y轴的偏移量
//
//                if (Math.abs(offsetX) > Math.abs(offsetY)) {
//                    //若X轴的偏移量大于Y轴的偏移量，则表示在横向滑动，
//                    // 否则在纵 向滑动，若相同，则表示移动的时候没有移动，
//                    // 这里滑动的时候， 会不断的调用这个，一次滑动的距离等于多次的偏移量相加
//
//                    //横向滑动
//                    intercepted = true;
//                } else {
//                    //竖向滑动
//                    intercepted = false;
//                }
//
//                offsetsByX += offsetX;//不断移动的时候获得移动的X轴总偏移量
//
//                offsetsByY += offsetY;//获得Y轴总偏移量
//
//                startX = movedX;//把每次移动后的X坐标作为下次移动开始时的X坐标
//
//                startY = movedY;//把每次移动后的Y坐标作为下次移动开始时的Y坐标
//
//                break;
//
//            case MotionEvent.ACTION_UP:
//
////                if (Math.abs(offsetsByX) > Math.abs(offsetsByY)) {
////                    //若X的总偏移量大于Y的总偏移量说明是X轴方向的滑动，否则是Y 轴方向的滑动
////                    if (offsetsByX > 0) {
////                        //若大于0则表示向左移动，若小于0则表示向右移动
////                    }
////                } else {
////                    if (offsetsByY > 0) {
////                        //做大于0则表示向下移动，若小于0则表示向上移动
////                    }
////                }
//                break;
//        }
//        return intercepted;

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        View parent = (View) getParent();
        //获取到手指处的横坐标和纵坐标
        int x = (int) event.getX();
        int y = (int) event.getY();
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                break;
            case MotionEvent.ACTION_MOVE:
                //计算移动的距离
                int offX = x - downX;
                int offY = y - downY;
                float targetX = getX() + offX;
                float targetY = getY() + offY;
                if (targetX < 0 || getWidth() + targetX > parent.getWidth()) {
                    return true;
                }
                setX(targetX);
                if (targetY < 0 || getHeight() + targetY > parent.getHeight()) {
                    return true;
                }
                setY(targetY);
                break;
            case MotionEvent.ACTION_UP:
                if (downX == getX() && downY == getY()) {
                    performClick();
                }
                break;
        }

        return true;
    }

    @Override
    public boolean performClick() {
        return super.performClick();
    }


    public static List<LogBean> sLogBeans = new ArrayList<>();

    public static class LogAdapter extends RecyclerView.Adapter<LogHolder> {

        public void setList(List<LogBean> list) {
            sLogBeans = list;
        }

        public void addLog(LogBean log) {
            if (sLogBeans.size() >= 50) {
                sLogBeans.remove(0);
                notifyItemRemoved(0);
            }

            int index = -1;
            for (int i = 0; i < sLogBeans.size(); i++) {
                LogBean logBean = sLogBeans.get(i);
                int id = logBean.getId();
                if (id == log.getId()) {
                    sLogBeans.set(i, log);
                    index = i;
                    break;
                }
            }
            if (index == -1) {
                sLogBeans.add(log);
                notifyItemInserted(sLogBeans.size() - 1);
            }else {
                notifyItemChanged(index);
            }
            if (mRecyclerView != null) {
                mRecyclerView.scrollToPosition(getItemCount() - 1);
            }
        }

        public List<LogBean> getList() {
            return sLogBeans;
        }

        @NonNull
        @Override
        public LogHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            Context context = parent.getContext();
            LinearLayout linearLayout = new LinearLayout(context);
            return new LogHolder(linearLayout);
        }

        @SuppressLint("SetTextI18n")
        @Override
        public void onBindViewHolder(@NonNull final LogHolder holder, int position) {
            final LogBean log = sLogBeans.get(position);
            int code;
            try {
                code = Integer.parseInt(log.getStatusCode());
            } catch (NumberFormatException e) {
                code = 0;
            }
            if (code >= 200 && code < 300) {
                holder.itemView.setBackgroundColor(GREEN);
            } else if (code == 0) {
                holder.itemView.setBackgroundColor(Color.GRAY);
            } else {
                holder.itemView.setBackgroundColor(Color.RED);
            }

            final Throwable exception = log.getException();
            if (exception != null) {
                final String message = exception.getMessage();
                log.setMessage(exception.getMessage());
                holder.tvSummary.setText(message);
                holder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        ErrorDialog dialog = new ErrorDialog(ActivityManger.getTopActivity());
                        dialog.setCancelable(true);
                        dialog.show();
                        dialog.bindData(log);
//                        Dialog dialog = new Dialog(ActivityManger.getTopActivity());
//                        TextView textView = new TextView(ActivityManger.getTopActivity());
//                        textView.setText(Arrays.toString(exception.getStackTrace()));
//                        dialog.setContentView(textView);
//                        dialog.setCanceledOnTouchOutside(true);
//                        dialog.show();
                    }
                });
            } else {
                holder.tvSummary.setText(log.getPath());
                holder.itemView.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        LogDetailDialog dialog = new LogDetailDialog(ActivityManger.getTopActivity());
                        dialog.setLog(log);
                        dialog.show();
                    }
                });
            }
            holder.tvTitle.setText(log.getRequestTime());


        }

        @Override
        public int getItemCount() {
            return sLogBeans == null ? 0 : sLogBeans.size();
        }

    }

    public static final int GREEN = Color.parseColor("#E655C456");

    static class LogHolder extends RecyclerView.ViewHolder {
        TextView tvTitle;
        TextView tvSummary;

        public LogHolder(@NonNull View itemView) {
            super(itemView);
            LinearLayout linearLayout = (LinearLayout) itemView;
            linearLayout.setBackgroundColor(GREEN);
            MarginLayoutParams params = new MarginLayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            params.topMargin = mDp5;
            params.leftMargin = mDp5;
            params.rightMargin = mDp5;
            linearLayout.setPadding(mDp5, mDp5, mDp5, mDp5);
//            params.bottomMargin = mDp5;
            linearLayout.setLayoutParams(params);
            linearLayout.setOrientation(VERTICAL);
            tvTitle = new TextView(itemView.getContext());
//            tvTitle.setMaxLines(1);
            tvTitle.setTextColor(Color.WHITE);
            linearLayout.addView(tvTitle);
            tvSummary = new TextView(itemView.getContext());
            tvSummary.setMaxLines(1);
            tvSummary.setEllipsize(TextUtils.TruncateAt.END);
            tvSummary.setTextColor(Color.WHITE);
            linearLayout.addView(tvSummary);
        }
    }

}


